package com.sunwayworld.baseline.framework.deviceDocking.boneequipt;

import com.sunwayworld.baseline.framework.deviceDocking.constant.InstrumentNameConstants;
import com.sunwayworld.baseline.framework.deviceDocking.handler.MessageHandler;
import com.sunwayworld.baseline.framework.deviceDocking.handler.MessageObservable;
import com.sunwayworld.framework.netty.core.server.NettyServerConfig;
import com.sunwayworld.framework.netty.core.server.NettyServerStarter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

@Service
public class ServiceHolder {

    @Value("${equipt-bone.port}")
    private int port;

    @Autowired
    private MessageObservable observer;

    // 自动启动服务
    @PostConstruct
    public void start() {
        // 血液分析仪服务
        NettyServerConfig config = new NettyServerConfig();
        config.setLocalAddress(new InetSocketAddress(port));
        config.setWorkerGroupChannelHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ch.pipeline()
                        // 添加解码器
                        .addLast(new StringDecoder(StandardCharsets.UTF_8))
                        // 添加编码器
                        .addLast(new StringEncoder(StandardCharsets.UTF_8))
                        // 添加消息处理器
                        .addLast(new MessageHandler(observer, InstrumentNameConstants.TG_XY));
            }
        });
        NettyServerStarter.of(config).start();
    }

}
